/*
 * @Author: your name
 * @Date: 2020-12-08 13:32:28
 * @LastEditTime: 2021-04-29 22:05:51
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /bridge-tunnel-ui/src/store/modules/user.js
 */
import { getToken, setToken, removeToken } from '@/utils/auth'
import rest from '@/store/rest.js'

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
    selection: 1, // 1: 下载列表  2: 收藏列表
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_SELECTION: (state, data) => {
      state.selection = data
    },
  },
  actions: {
    setSelection({ commit }, data) {
      commit('SET_SELECTION', data)
    },
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    async userFeedback ({ commit }, data) { // 用户反馈
      const res = await rest.post('user/feedback', data)
      if (res && res.code === 200) {
        return true
      }
      return false
    },
    async getUserCollection({ commit }, data) { // 用户收藏列表
      const res = await rest.get('user/collect_list', data)
      if (res && res.code === 200) {
        return res.data
      }
      return {}
    },
    async getUserDownload({ commit }, data) { // 用户下载列表
      const res = await rest.get('user/download_list', data)
      if (res && res.code === 200) {
        return res.data
      }
      return {}
    },
    async doDownload ({ commit }, data) { // 下载
      const res = await rest.get('user/download', data)
      console.log('doDownload', res)
      if (res && res.code === 200) {
        return true
      }
      return false
    },
    async doCollection({ commit }, data) { // 收藏
      const res = await rest.get('user/collect', data)
      console.log('doCollection', res)
      if (res && res.code === 200) {
        return true
      }
      return false
    },
    async cancelCollection({ commit }, data) {// 取消收藏
      const res = await rest.get('user/cancel_collect', data)
      console.log('cancelCollection', res)
      if (res && res.code === 200) {
        return true
      }
      return false
    },
    async Login({ commit }, data) { // 登录
      const res = await rest.get('auth/login', data)
      return res
    }
  },
  getters: {
    selection: (state) => state.selection // 1: 下载列表  2: 收藏列表
  }
}

export default user
